interface TagInterface {
  name: string
}
interface RowInterface {
  categories: Array<{ name: string }>
  comments: string[]
  content: string
  createdAt: string
  id: number
  tags: Array<{ name: string }>
  title: string
  updatedAt: string
  viewCount: number
}
type FieldType = {
  title?: string
  content?: string
  tagList?: Array<{ name: string }>
  categoryList?: Array<{ name: string }>
}
import { useEffect, useState } from "react"
import http from "@/utils/http"
import {
  Button,
  Space,
  Table,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  Row,
  Col,
} from "antd"
import type { TableProps } from "antd"
import { message } from "antd"
import { SearchOutlined } from "@ant-design/icons"
import { useTranslation } from "react-i18next"
const { Search } = Input
const Index = () => {
  const { t } = useTranslation()
  const columns: TableProps<RowInterface>["columns"] = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      render: text => <a>{text}</a>,
    },
    {
      title: "文章内容",
      dataIndex: "content",
      key: "content",
    },
    {
      title: "标签",
      dataIndex: "tags",
      key: "tags",
      render: text =>
        text.map((item: TagInterface, ind: string) => (
          <Tag key={ind} color="blue">
            {item.name}
          </Tag>
        )),
    },
    {
      title: "分类",
      dataIndex: "categories",
      key: "categories",
      render: text =>
        text.map((item: TagInterface, ind: string) => (
          <Tag key={ind} color="blue">
            {item.name}
          </Tag>
        )),
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
    },
    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => handelEdit(record)}>编辑</Button>
          <Button danger>删除</Button>
        </Space>
      ),
    },
  ]
  const token = localStorage.getItem("token")
  const [form] = Form.useForm()
  const [artcileData, setArticleData] = useState()
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [count, setCount] = useState()
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(7)
  // 编辑的id
  const [editId, setEditId] = useState<number>()
  // 判断新增还是编辑的依据
  const [flag, setFlag] = useState(false)
  // 文章的id
  const [] = useState()
  // 用户id
  const [authorId, setAuthorId] = useState(() => {
    const userInfo = localStorage.getItem("userInfo")
    if (userInfo) return JSON.parse(userInfo).userId
  })
  useEffect(() => {
    getArticle()
  }, [page, pageSize])
  async function getArticle(keyword?: string, tag?: string) {
    try {
      const res = await http.get("/article/list", {
        params: {
          page,
          setPageSize,
          keyword,
          tag,
        },
      })
      console.log(res)
      setArticleData(res.data.rows)
      setCount(res.data.count)
    } catch (error) {
      message.error("获取失败")
      console.error(error)
    }
  }
  // 编辑文章
  const handelEdit = (row: RowInterface) => {
    setEditId(row.id)
    setFlag(false)
    setIsModalOpen(true)
    form.setFieldsValue({
      title: row.title,
      content: row.content,
      tagList: row.tags.map(item => item.name),
      categoryList: row.categories.map(item => item.name),
    })
  }
  // 新增文章
  const handelAdd = () => {
    setFlag(true)
    setIsModalOpen(true)
    form.resetFields()
  }
  const handleCancel = () => {
    setIsModalOpen(false)
  }
  const handleOk = async () => {
    try {
      const values = await form.getFieldsValue()
      if (flag) {
        // 新增时携带的参数
        const createParms = {
          title: values.title,
          content: values.content,
          tagList: values.tagList || [],
          categoryList: values.categoryList || [],
          authorId,
        }
        const res = await http.post(
          "/article",
          createParms,
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        )
        if (res.status === 200) {
          message.success("新增成功")
          getArticle()
        } else {
          message.error("新增失败")
        }
      } else {
        // 编辑时携带的参数
        const editParmas = {
          title: values.title,
          content: values.content,
          tagList: values.tagList,
          categoryList: values.categoryList,
        }
        console.log(editParmas)
        await http.put(`/article/${editId}`, editParmas, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        })
        message.success("编辑成功")
        getArticle()
      }
    } catch (error) {}
    setIsModalOpen(false)
  }
  // 切换页码数
  const handelPage = (page: number, pageSize: number) => {
    setPage(page)
    setPageSize(pageSize)
  }
  // 标题的搜索
  const onKeywordSearch = (val: string) => {
    getArticle(val)
  }
  // 标签的搜索
  const onTagSearch = (val: string) => {
    getArticle("", val)
  }
  return (
    <div>
      <h2
        style={{ background: "var(--bg--color)", color: "var(--text--color)" }}>
        {t("menu.title")}
      </h2>
      <Row>
        <Col>
          <Search
            placeholder="输入文章标题"
            allowClear
            enterButton={<SearchOutlined />}
            size="large"
            onSearch={onKeywordSearch}
          />
        </Col>
        <Col>
          <Search
            placeholder="输入文章标签"
            allowClear
            enterButton={<SearchOutlined />}
            size="large"
            onSearch={onTagSearch}
          />
        </Col>
      </Row>
      <Button type="primary" onClick={() => handelAdd()}>
        新增
      </Button>
      <Table<RowInterface>
        style={{ background: "var(--bg--color)", color: "var(--text--color)" }}
        columns={columns}
        dataSource={artcileData}
        rowKey="id"
        pagination={{
          onChange: handelPage,
          total: count,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: count => `Total ${count} items`,
        }}
      />
      {/* Modal框 */}
      <Modal
        title={flag ? "新增" : "编辑"}
        closable={{ "aria-label": "Custom Close Button" }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}>
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{
            title: "", // 初始化为空字符串
            content: "", // 初始化为空字符串
            tagList: [], // 初始化为空数组
            categoryList: [], // 初始化为空数组
          }}
          autoComplete="off">
          <Form.Item<FieldType>
            rules={[
              {
                required: true,
                message: "请输入文章标题",
              },
            ]}
            label="文章标题"
            name="title">
            <Input />
          </Form.Item>
          <Form.Item<FieldType>
            rules={[
              {
                required: true,
                message: "请输入文章内容",
              },
            ]}
            label="文章内容"
            name="content">
            <Input />
          </Form.Item>
          <Form.Item<FieldType> label="标签(可选)" name="tagList">
            <Select
              mode="tags"
              style={{ width: "100%" }}
              placeholder="输入选择,按回车添加"
              allowClear
            />
          </Form.Item>
          <Form.Item<FieldType> label="分类(可选)" name="categoryList">
            <Select
              mode="tags"
              style={{ width: "100%" }}
              placeholder="输入选择,按回车添加"
              allowClear
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Index
